package com.android.aqq;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import edu.tsinghua.lumaqq.qq.QQ;
import edu.tsinghua.lumaqq.qq.beans.QQUser;
import edu.tsinghua.lumaqq.qq.events.QQEvent;
import edu.tsinghua.lumaqq.qq.packets.in._09.LoginRequestReplyPacket;
import edu.tsinghua.lumaqq.qq.packets.in._09.LoginVerifyReplyPacket;

public class LoginActivity extends Activity {
	private static final int DIALOG_MESSAGE = 0;
	private static final int DIALOG_SERVER =1;
	private Button mLoginButton = null; //登录按钮
	private String message;
	private QQService mBoundService;
	private ProgressDialog progressDialog = null;
	private String account;
	private String password;
	private boolean savePassword = false;
	private AutoCompleteTextView mAccountEdit;
	private NotificationManager mNotificationManager;
	private CheckBox mSavePwdCheckBox; //是否保存密码
	private CheckBox mHiddenLoginBox; //是否隐身登录
	private TextView mPasswordEdit;
	private CheckBox mMuteCheckBox; //是否静音
	private CheckBox mGroupImCheckBox; //是否接受群消息
	private SharedPreferences mSharedPref;
	private Menu mMenu;
	
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		int orientation = this.getResources().getConfiguration().orientation;
//		if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
//			setContentView(R.layout.login_v);
//		} else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
//			setContentView(R.layout.login);
//		}
		setContentView(R.layout.login);
		startService(new Intent(LoginActivity.this, QQService.class));
		mSharedPref = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
		//绑定服务
		bindService(new Intent(LoginActivity.this, QQService.class), mConnection, Context.BIND_AUTO_CREATE);
		
		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		
		mAccountEdit = (AutoCompleteTextView) findViewById(R.id.account_edit);
		mAccountEdit.setAdapter(getAutoCompleteAdapter());
		
		mPasswordEdit = (TextView) findViewById(R.id.password_edit);
		mSavePwdCheckBox = (CheckBox) findViewById(R.id.save_password_checkbox);
		mHiddenLoginBox = (CheckBox) findViewById(R.id.hidden_login_checkbox);
		mMuteCheckBox = (CheckBox) findViewById(R.id.mute_checkbox);
		mGroupImCheckBox = (CheckBox) findViewById(R.id.group_im_checkbox);
		
		//设置选择框状态
		mSavePwdCheckBox.setChecked(mSharedPref.getBoolean("SAVE_PASSWORD", true));
		mHiddenLoginBox.setChecked(mSharedPref.getBoolean("HIDDEN_LOGIN", false));
		mMuteCheckBox.setChecked(mSharedPref.getBoolean("MUTE_LOGIN", false));
		mGroupImCheckBox.setChecked(mSharedPref.getBoolean("RECEIVE_GROUP_IM", false));
		
		savePassword = mSavePwdCheckBox.isChecked();
		
		mLoginButton = (Button) findViewById(R.id.ButtonLogin);
        mLoginButton.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				//记录选择框状态
				SharedPreferences.Editor editor = mSharedPref.edit();
				editor.putBoolean("SAVE_PASSWORD", mSavePwdCheckBox.isChecked());
				editor.putBoolean("HIDDEN_LOGIN", mHiddenLoginBox.isChecked());
				editor.putBoolean("MUTE_LOGIN", mMuteCheckBox.isChecked()); //是否静音
				editor.putBoolean("RECEIVE_GROUP_IM", mGroupImCheckBox.isChecked()); //是否接受群消息
				editor.commit();
				
	            //获得QQ账户密码
	            account = mAccountEdit.getText().toString();
	            password = mPasswordEdit.getText().toString();
	            //是否保存密码
	            savePassword = mSavePwdCheckBox.isChecked();
	            
	            //是否隐身
	            final boolean isHidden = mHiddenLoginBox.isChecked();
	            
	            progressDialog = ProgressDialog.show(LoginActivity.this, getText(R.string.title_waiting),
						getText(R.string.progress_logining), true);
	            progressDialog.setCancelable(false);
	            new Thread() {
	      			public void run() {
	      				// 登录	
	      	            mBoundService.startLogin(account, password, isHidden);
	      		    }
	      		}.start();
	    	}
	    });
        
        mAccountEdit.setOnItemClickListener(new OnItemClickListener(){
			public void onItemClick(AdapterView<?> av, View v, int pos,
					long id) {
				if (savePassword) {
					mPasswordEdit.setText(mSharedPref.getString("PASSWORD" + pos, ""));
				}
			}
        	
        }) ;
	}

	@Override
	protected void onStart() {
		super.onStart();
		mAccountEdit.setText(mSharedPref.getString("CUR_ACCOUNT", ""));
		if (savePassword) {
			mPasswordEdit.setText(mSharedPref.getString("CUR_PASSWORD", ""));
		}
	}

	private ArrayAdapter<String> getAutoCompleteAdapter() {
		int count = mSharedPref.getInt("ACCOUNT_NUM",0);
		String[] accounts = new String[count];
		for (int i=0; i<count; i++) {
			accounts[i] = mSharedPref.getString("ACCOUNT"+i, "");
		}
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, accounts);
		return adapter;
	}
	
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	QQEvent event = null;
        	switch(msg.what) {
        	/*    登录事件           */
        	case QQEvent.LOGIN_NEED_VERIFY: //登录需要验证
        		event = (QQEvent)msg.obj;
        		processLoginRequestVerify((LoginRequestReplyPacket) event.getSource());
        		break;
        	case QQEvent.LOGIN_OK:
        		if(!QQService.hasDataDownloaded) { //未下载数据，用于第一次登录
        			progressDialog.setMessage(getText(R.string.progress_downloading));
            		//保存qq号码
            		saveAccount();
            		//下载好友列表
            		mBoundService.downloadFriends();
        		} else { //已经下载数据，用于重新登录
        			startMainActivity();
        		}
        		break;
        	case QQEvent.FRIEND_GET_LIST_OK:
    			QQService.hasDataDownloaded = true;
    			startMainActivity();
        		break;
        	case QQEvent.LOGIN_FAIL:
        		event = (QQEvent) msg.obj;
        		progressDialog.dismiss();
        		LoginVerifyReplyPacket vp = (LoginVerifyReplyPacket) event.getSource();
        		message = "登录时发生错误：" + vp.replyCode + "：" + vp.replyMessage;
        		showDialog(DIALOG_MESSAGE);
        		break;
        	case QQEvent.LOGIN_UNKNOWN_ERROR: //登录错误
        		event = (QQEvent) msg.obj;
        		progressDialog.dismiss();
        		message = "登录时发生未知错误";
        		showDialog(DIALOG_MESSAGE);
        		break;
        	case QQEvent.SYS_TIMEOUT: //系统超时
        		event = (QQEvent) msg.obj;
        		switch(event.operation) {
		        case QQ.QQ_CMD_LOGIN:
		        case QQ.QQ09_CMD_LOGIN_TOUCH:
		        case QQ.QQ09_CMD_LOGIN_REQUEST:
		        case QQ.QQ09_CMD_LOGIN_GET_INFO:
		        case QQ.QQ09_CMD_LOGIN_SEND_INFO:
		        case QQ.QQ09_CMD_LOGIN_VERIFY:
		        	progressDialog.dismiss();
	        		message = getResources().getString(R.string.info_login_timeout);
	        		showDialog(DIALOG_MESSAGE);
		        	break;
		        default:
		        	progressDialog.dismiss();
		        	mBoundService.logout();
        			message = getResources().getString(R.string.info_sys_timeout);
        			showDialog(DIALOG_MESSAGE);
		        	break;
        		}
        		
        		break;
        	 case -1:
        		progressDialog.dismiss();
             	message = (String)msg.obj;
             	showDialog(DIALOG_MESSAGE);
             	break;
//        	default:
//        		progressDialog.dismiss();
//    			message = "事件代码：" + Integer.toHexString(msg.what);
//    			showDialog(DIALOG_MESSAGE);
//    			break;
        	}
        }

		private void startMainActivity() {
			//取消绑定服务
			unbindService(mConnection);
			//启动QQ主界面
			startActivity(new Intent(LoginActivity.this, aQQActivity.class));
			progressDialog.dismiss();
			finish();
		}

		private void processLoginRequestVerify(LoginRequestReplyPacket in) {
			Bitmap bmImg = BitmapFactory.decodeByteArray(in.pngData, 0, in.pngData.length);
			
			LayoutInflater factory = LayoutInflater.from(LoginActivity.this);
			final View authView = factory.inflate(R.layout.add_friend_auth_img_dialog, null);
			final ImageView iv = (ImageView)authView.findViewById(R.id.auth_img);
			final TextView tv = (TextView)authView.findViewById(R.id.auth_img_edit);
			final byte[] answerToken =  in.answerToken;
			
			iv.setImageBitmap(bmImg);
			
			new AlertDialog.Builder(LoginActivity.this)
			.setTitle("请输入验证码")
			.setView(authView)
			.setPositiveButton(R.string.button_confirm, new DialogInterface.OnClickListener() {
			    public void onClick(DialogInterface dialog, int whichButton) {
			    	Log.d("aQQ", "authInfo=" + tv.getText().toString());
			    	//提交验证信息
			    	mBoundService.loginRequestVerify(answerToken, tv.getText().toString());
			    }
			})
			.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
			    public void onClick(DialogInterface dialog, int whichButton) {
			    	progressDialog.dismiss();
			    }
			})
			.show();
		}

		private void saveAccount() {
			int count = mSharedPref.getInt("ACCOUNT_NUM",0);
			int pos = -1;
			for (int i=0; i<count; i++) {
				if (account.equals(mSharedPref.getString("ACCOUNT"+i, ""))) {
					pos = i;
					break;
				}
			}
			
			SharedPreferences.Editor editor = mSharedPref.edit();
			if (pos == -1){ //没有找到该账号，把新账号加入配置中
				editor.putString("ACCOUNT" + count, account);
				editor.putInt("ACCOUNT_NUM", count+1);
				pos = count;
			} 
			editor.putString("CUR_ACCOUNT", account);
			if (savePassword) {
				editor.putString("CUR_PASSWORD", password);
				editor.putString("PASSWORD" + pos, password);
			} else {
				editor.remove("PASSWORD" + pos);
				editor.remove("CUR_PASSWORD");
			}

			editor.commit();
		}
    };
    
//	@Override
//	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//		super.onActivityResult(requestCode, resultCode, data);
//		if (requestCode == 0) {
//			if (resultCode == RESULT_CANCELED) {
//				message = data.getStringExtra("MESSAGE");
//				showDialog(DIALOG_MESSAGE);
//			}
//			if (resultCode == RESULT_OK) {
//				finish();
//			}
//        }
//	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
        case DIALOG_MESSAGE:
            return new AlertDialog.Builder(LoginActivity.this)
			.setMessage(message)
			.setPositiveButton(R.string.button_confirm,
			new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface arg0, int arg1) {

				}
			}).create();
		}
		return null;
	}
	
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
		switch(id) {
		case DIALOG_MESSAGE:
			AlertDialog alert = (AlertDialog) dialog;
			alert.setMessage(message);
			break;
		}
	}
	
	private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mBoundService = ((QQService.LocalBinder)service).getService();
            mBoundService.setControlHandler(mHandler);
            QQUser user = mBoundService.getUser();
            if (user!=null && user.isLoggedIn()) {
            	//取消绑定服务
    			unbindService(mConnection);
        		//启动QQ主界面
 	           	startActivity(new Intent(LoginActivity.this, aQQActivity.class));
 	           	finish();
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            mBoundService = null;
        }
    };
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        	mNotificationManager.cancel(aQQActivity.NOTIFICATION_STATUS);
        }
        return super.onKeyDown(keyCode, event);
    }
    
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
    	 mMenu = menu;
         MenuInflater inflater = getMenuInflater();
         inflater.inflate(R.menu.menu_login, menu);
         return true;
    }
    
    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
        switch (item.getItemId()) { 
    	case R.id.menu_preference:
    		startActivity(new Intent(LoginActivity.this, aQQPref.class));
            break;

        }
        return super.onOptionsItemSelected(item);
    }
}
